import { Controller, Post, UseGuards, Body, Req, Get, Put } from '@nestjs/common';
import { AuthGuard } from '../guard/auth.guard';
import { CommonResult } from '../utils/result';
import { TaskService } from './task.service';

@Controller('task')
export class TaskController {
  constructor(private readonly taskService: TaskService) {}

  @Post('/createTask')
  @UseGuards(AuthGuard)
  async createUserTask(@Body() body) {
    // 同一个任务不能创建多次
    if (body.taskName === '' || body.sendTime === '') {
      return CommonResult(null, false, 401, '任务名称和发送时间不能为空');
    }
    const result = await this.taskService.createTask(body);
    return CommonResult(result, true, 200, '创建成功');
  }

  @Get('/list')
  @UseGuards(AuthGuard)
  async getUserCronTaskList(@Req() req) {
    const reuslt = await this.taskService.getTaskList(req.user);
    return CommonResult(reuslt, true, 200, '获取成功');
  }

  @Post('/delete')
  @UseGuards(AuthGuard)
  async deleteTask(@Body() body) {
    const result = await this.taskService.deleteTask(body.id);
    return CommonResult(result, true, 200, '删除成功');
  }
  @Put('/userTaskState')
  @UseGuards(AuthGuard)
  async updateTaskState(@Body() body) {
    const result = await this.taskService.setTaskState(body.id, body.taskState);
    return CommonResult(result, true, 200, '设置成功');
  }

  @Post('/startTask')
  @UseGuards(AuthGuard)
  async startTask(@Body() body) {
    this.taskService.startCronJob(String(body.id), body.sendTime);
    return CommonResult(null, true, 200, '启动成功');
  }

  @Post('/removeTask')
  @UseGuards(AuthGuard)
  async removeTask(@Body() body) {
    this.taskService.setTaskState(body.id, 'on');
    const reuslt = this.taskService.deleteCron(String(body.id));
    return CommonResult(reuslt, true, 200, '移除成功');
  }
}
